import * as _ from "lodash"
import { camelCase, snakeCase } from "../case"
import { PageList } from "../data"
import httpClient from "../httpclient"

export enum HolderType {
  Individual = "individual",
  Company = "company"
}

export enum BankCardFunding {
  Credit = "credit",
  Debit = "debit",
  Prepaid = "prepaid",
  Unknown = "unknown"
}

export class BankCard {
  public id: string
  public accountId: string
  public funding: BankCardFunding
  public bankName: string
  public branchName: string
  public holderType: HolderType
  public holderName: string
  public number: string
  public last4: string
  public expiryYear: string
  public expiryMonth: string
  public createdTime: string
}

export class BankCardQuery {

  private params = {}

  public page(page?: string | number): BankCardQuery {
    if (page) {
      this.params["page"] = page
    }
    return this
  }

  public limit(limit?: string | number): BankCardQuery {
    if (limit) {
      this.params["limit"] = limit
    }
    return this
  }

  public accountId(accountId?: string): BankCardQuery {
    this.params["account_id"] = accountId
    return this
  }

  public list(): Promise<PageList<BankCard>> {
    return httpClient.get("/v1/bank-cards", {
      params: this.params,
    }).then(({ data }) => data)
      .then(camelCase)
      .then(data => {
        return _.assign(new PageList<BankCard>(), data, {
          elements: _.map(data.elements, card => _.assign(new BankCard(), card)),
        })
      })
  }

}

export class BankCardServiceV1 {

  public static createBankCardQuery() {
    return new BankCardQuery()
  }

  public static bindBankCard(bankCard: BankCard): Promise<BankCard> {
    return httpClient.post(`/v1/bank-cards`, snakeCase(bankCard))
      .then(({ data }) => data)
      .then(camelCase)
      .then(data => _.assign(new BankCard(), data))
  }

  public static updateBankCard(bankCard: BankCard): Promise<BankCard> {
    return httpClient.patch(`/v1/bank-cards/${bankCard.id}`, snakeCase(bankCard))
      .then(({ data }) => data)
      .then(camelCase)
      .then(data => _.assign(new BankCard(), data))
  }

  public static unbindBankCard(id: string): Promise<void> {
    return httpClient.delete(`/v1/bank-cards/${id}`)
  }

}
